﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Nature.Core.Exceptions
{
    /// <summary>
    ///     该框架下，所有异常的基类，不可实例化
    /// </summary>
    public abstract class BaseException : Exception
    {
        #region 类管理内容

        //异常文件列表
        //static IList<string> _fileList = new List<string>();
        //异常信息内容
        private static readonly Dictionary<string, string> _exceptionDic = new Dictionary<string, string>();

        static BaseException()
        {
            _exceptionDic.Add("B0", "未找到异常编号{0}。");
            _exceptionDic.Add("B1", "异常编号{0}已存在。");
        }

        //添加异常
        public static void AddExceptions(string xmlPath)
        {
            var doc = new XmlDocument();
            doc.Load(xmlPath);
            //读取每个exception
            foreach (XmlNode node in doc.SelectNodes("exceptions/exception"))
            {
                string key = node.Attributes["code"].Value;
                if (_exceptionDic.ContainsKey(key))
                {
                    throw new FrameExcetpion("B1", new[] { key });
                }
                _exceptionDic.Add(key, node.InnerText);
            }
        }
        //初始化异常
        internal static void InitialException()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "Exceptions\\FrameExceptions.xml";
            AddExceptions(path);
        }

        #endregion

        public BaseException(string errNo, Exception innerException, string[] infos = null)
            : base(errNo, innerException)
        {
            ErrNo = errNo;
            string content = string.Empty;
            if (_exceptionDic.TryGetValue(errNo, out content))
            {
                if (infos != null)
                {
                    content = string.Format(content, infos);
                }
            }
            else
            {
                throw new FrameExcetpion("B0", new[] { errNo });
            }

            ExpContent = content;
        }

        public string ExpContent { get; private set; }

        public string ErrNo { get; private set; }

        public override string Message
        {
            get { return ExpContent; }
        }

        public override string ToString()
        {
            string content = "异常编号：" + ErrNo + "\n异常内容：" + ExpContent + "\n" + base.ToString();
            return content;
        }
    }
}
